// Copyright (C) 2025, ZWSOFT Co., LTD.(Guangzhou)
// Licensed under the MIT License. See LICENSE in the project root for license information.

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using TestClient.Domain;

namespace TestClient.ViewModel;
public partial class CurveDivisionTestViewModel : PageViewModelBase
{
    [ObservableProperty]
    private string curveId = string.Empty;
    [ObservableProperty]
    private int numPoints = 3;
    [ObservableProperty]
    private string pointsFormatted = string.Empty;

    public IAsyncRelayCommand SelectCurveCommand { get; }
    public IAsyncRelayCommand DivideCurveCommand { get; }
    public IAsyncRelayCommand DivideRingCommand { get; }
    public IAsyncRelayCommand DismantleCurveCommand { get; }

    public CurveDivisionTestViewModel(VFAdapterWrapper wrapper, ISnackNotifyService notifyService) : base(wrapper, notifyService)
    {
        SelectCurveCommand = CreateAsyncRpcCommand(SelectCurve);
        DivideCurveCommand = CreateAsyncRpcCommand(DivideCurve);
        DivideRingCommand = CreateAsyncRpcCommand(DivideRing);
        DismantleCurveCommand = CreateAsyncRpcCommand(DismantleCurve);
    }

    private async Task SelectCurve()
    {
        EnsureConnected();
        CurveId = await ViewModelHelpers.SelectEnt(Wrapper, "Curve");
    }

    private async Task DivideCurve()
    {
        EnsureConnected();
        var points = await Task.Run(() =>
        {
            return Wrapper.GetEquidistantPointsOnCurve(CurveId, NumPoints);
        });
        // to string and join by comma
        PointsFormatted = string.Join(", ", points.Select(p => p.ToString()));
    }

    private async Task DivideRing()
    {
        EnsureConnected();
        var points = await Task.Run(() =>
        {
            return Wrapper.GetEquidistantPointsOnCurveRing(CurveId, NumPoints);
        });
        // to string and join by comma
        PointsFormatted = string.Join(", ", points.Select(p => p.ToString()));
    }

    private async Task DismantleCurve()
    {
        EnsureConnected();
        var (segments, types) = await Task.Run(() =>
        {
            Wrapper.DismantleCurve(CurveId, out var segments, out var type);
            return (segments, type);
        });
        PointsFormatted = string.Join(", ", segments) + "; Type: " + string.Join(", ", types);
    }
}
